javascript - Why are jQuery objects in property initialization empty? -
'use strict'; var controller = function controller() {}; controller.init = function() { if (!controller.propertie.element || !controller.propertie.indicator) { return 'expected find [data-controller] , [data-controller-to]'; } controller._start(); }; controller.propertie = { element: $('[data-controller]'), indicator: $('[data-controller-to]'), state: false }; controller._start = function() { controller.propertie.indicator.bind('click', controller._toggle); }; controller._toggle = function() { controller.propertie.element .animate({ bottom: (controller.propertie.state = !controller.propertie.state) ? '-110' : '0' }); };
apparently elements in object property not exist, exist ! tell me if can not use javascript that?
maybe there hoisting breaking script?
i try put object before init , result same.
i know can extend prototype, have reasons use this.
thanks.
i can think of 3 possible causes:
- the code being initialized before dom has been parsed.
- your html not contain elements match these selectors.
- the desired elements being created dynamically after code being initialized.
in declaration:
controller.propertie = { element: $('[data-controller]'), indicator: $('[data-controller-to]'), state: false };
the 2 jquery expressions evaluated code parsed. if code not placed @ end of body, elements not exist yet.
the usual solution not initialize elements in static declaration, initialize them calling function after page has been loaded.
if intend them globals, this:
$(document).ready(function() { controller.propertie = { element: $('[data-controller]'), indicator: $('[data-controller-to]'), state: false }; });
but, have make sure don't try use them until after code runs.
the other possible cause can think of dom not contain elements match 2 selectors. seems it's 1 of these 2 issues. since haven't shown either overall page structure of html intend match, it's impossible other tell causes might be.
Comments
Post a Comment