vendredi 9 janvier 2015

MVP pattern and event delegation in javascript

In my project I'm using the MVP pattern in this way:


planningView.js



function view(onInit){

function init(){
var id = xyz;
onInit(id);
}

init();
return{

create: function(data-from-model){
// page view setup:
// add the elements in the view to
// create page's structure
},

onChangeYear : function(handler){

$("div.page").on("change", "select.year", function(){
var year = Number($(this).val());
handler(year);
});
}
}
}


planningPresenter.js



var model = planningModel(culture);

var view = planningView(function(id){

model.load(id).done(function(data-from-model){

view.create(data-from-model);
});

});

view.onChangeYear(function(year){
//contact model using year, etc...
});


With this code, in the onChangeYear, I can bind the event only if I use the first not dynamic parent element "div.page" because "select.year" is created in view.create().


The question is: How could I organize the code to using onChangeYear in this way?



onChangeYear : function(handler){

$("select.year").on("change", function(){
var year = Number($(this).val());
handler(year);
});
}

Aucun commentaire:

Enregistrer un commentaire