Knockout.js - When using templates, how do I know to which dom element a given model is bound? -


i have page i'm repeating large sections using foreach:

<div class="module-wrapper"    data-bind="template: { name: 'dependent-template', foreach: dependentinformation }">     </div> 

i'm setting logic in these sections , need run jquery (addclass()) when model value changes. can't figure out how handle on current model's bound dom element.

anyone know this?

update

when reading afterrender, saw afteradd, i'm using:

<div class="module-wrapper"         data-bind="template: {           name: 'dependent-template',           foreach: dependentinformation,           afteradd: setclassfrommodelstate }"> </div> 

this wasn't clean have liked because, although have 2 items in dependentinformation array, afteradd() called 4 times each item (text, dom object, comment, , text).

so, have inspect element know when want:

self.setclassfrommodelstate = function(element, index, data){     if ($(element).hasclass("cat") && $(element).hasclass("form-group")) {         $(element)             .removeclass("off")             .removeclass("summary")             .removeclass("edit")             .addclass(data.model_state());     } }; 

would rather have cleaner way this... working...

another update

just read here should check node type want:

self.setclassfrommodelstate = function(element, index, data){    if (element.nodetype === 1) {         $(element)            .removeclass("off")            .removeclass("summary")            .removeclass("edit")            .addclass(data.model_state());    } }; 

http://jsfiddle.net/rniemeyer/awcrm/2/

the afterrender event of foreach binding give access generated dom.

afterrender — invoked each time foreach block duplicated , inserted document, both when foreach first initializes, , when new entries added associated array later. knockout supply following parameters callback:

  • an array of inserted dom elements
  • the data item against being bound

i hope helps.


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -