What is the preferred way to assign a jQuery object to a Javascript object for event binding? -


example:

i want create multi-window webapp. each window jquery object (with dom element attached it), should have specific properties , methods (such close() or minimize()). seems then, should create class mywindow property domelement contain jquery object.

but how bind dom events mywindow objects?

i mywindow.domelement.on('click', function(){...}. domelement doesn't know mywindow it's attached , won't able manipulate it's properties if needed. example, wouldn't able invoke it's mywindow's close() method.

i see 2 ways of solving problem.

first. extend jquery object in mywindow.domelement property single property mywindow point object's parent mywindow object.

second. extend jquery object mywindow's properties , make instanceof mywindow (through parasitic inheritance, perhaps?). way event handlers have access properties , methods of mywindow through use of this.

both ways seem weird.

what preferred way assign dom object javascript object event binding?

i in first solution:

mywindow objects containing relevant jquery object dom element 1 of properties:

var mywindow = function(params) {   this.close = function() {/*close window*/};   this.minimise = function() {/*minimise window*/};   this.$elm = $('#'+params.id);   // other stuff have initialise window    this.$elm.mywindow = this; } 

then bind click:

window1 = new mywindow({id: 'window'}); window1.$elm.on('click', function() {   this.close(); }); 

edit: alternative used have separate event handler routes events correct method of correct object requires keep track of ids correspond objects following code illustrates:

var mywindows = [];  var mywindow = function(params) {   // initialise object    mywindows[params.id] = this; };  $(function() {   $(document).on({     click: function(e) {       var mywindow = mywindows[$(this).attr('id')];       if (typeof mywindow.click === 'function') {         mywindow.click(e);       }     }   }, '.mywindow'); }; 

you bind events adding appropriate method object

var mywindow = new mywindow({'id': window});  mywindow.click = function(event) {   this.close(); }; 

however, danger approach have careful keeping mywindows array date or sorts of memory leaks (clearly difficulty/importance of depend on context of app).


Comments

Popular posts from this blog

.htaccess - First slash is removed after domain when entering a webpage in the browser -

Automatically create pages in phpfox -

c# - Farseer ContactListener is not working -