2013-04-27 2 views
7

KnockoutがhtmlをDOMに追加してレンダリングを完了した後にカスタムコードを実行する方法はありますか?私はこれを必要とするので、動的に追加されたHTMLコードにネストされたビューモデルをバインドすることができます。htmlバインディングのafterRender

ような何か:「update」イベントが呼び出されることが保証されていないため

<div data-bind="html: dynamicHtml, afterRender: customCode"></div> 

... 

MyViewModel.prototype.customCode = function(){ 
    ko.applyBindings(self.MyInnerViewModel(), document.getElementById('someTagInTheDynamicHtml')); 
}; 

afterRenderは、(?のみテンプレートバインディングで動作します)ここに呼ばれず、カスタムバインディングはどちらか助けていません。 DOMが更新された後

答えて

12

はい、afterRenderは、templateバインドのみで動作します。

しかし、htmlバインディングの変更を追跡し、値が更新されたときにコールバックを発生させるカスタムバインディングハンドラを作成できます。私の例:

ko.bindingHandlers.afterHtmlRender = { 
    update: function(el, va, ab){ 
     ab().html && va()(ab().html); 
    } 
} 

短縮のparam名:VA - valueAccessor、AB - allBindings。また

マークアップはそのようになっているはずです(バインディング名が変更された):

<div data-bind="html: dynamicHtml, afterHtmlRender: customCode"></div> 

http://jsfiddle.net/dDDjf/

アップデートを

説明付き

簡体バインディングコード:

ko.bindingHandlers.afterHtmlRender = { 
    update: function(element, valueAccessor, allBindings){ 
     // check if element has 'html' binding 
     if (!allBindings().html) return; 
     // get bound callback (don't care about context, it's ready-to-use ref to function) 
     var callback = valueAccessor(); 
     // fire callback with new value of an observable bound via 'html' binding 
     callback(allBindings().html); 
    } 
} 
+0

感謝- よく働く。私はそれが 'ab().html()'で始めるべきだと思います。また、人々が何が起こっているのか理解できるように、コードをリファクタリングしてもらえますか? – seldary

+0

いいえ、 'ab().html'があるはずです。それは、すべてのバインディング間の* html *バインディング存在のチェックだけです。私は説明で私の答えを更新しました。 –

関連する問題