开发者

Accessing to attributes of html tags inside knockoutjs template

开发者 https://www.devze.com 2023-03-25 20:00 出处:网络
I have a template like this: <script id=\"notesTemplate\" type=\"text/html\"> <li class=\"Note\">

I have a template like this:

<script id="notesTemplate" type="text/html">
<li class="Note">
    <div class="NoteDate" data-bind="style: { backgroundColor: background, color: color}">
            <span data-bind="text: date"></span>
        </div>
        <div class="NoteRight" data-bind="style: { backgroundColor: background, color: color}">
            <div class="NoteContent">
                <span data-bind="text: content"></span>
            </div>
            <div class="line" data-bind="style: { borderColor: color}"></div>
            <div class="NoteCategory" data-bind="style: { color: color}">
                <span data-bind="text: category"></span>
            </div>
        </div>
</li>
</script>

As you see, I create a simple list with notes (I set some css styles because every note item have its own bg and color but, is this the right way?) but:

I want to set the NoteDate div with height equal to the NoteRight div. I'm actually doing that in JS:

$(function () {
    ko.applyBindings(new viewModel());

    $(".Note").each(function (index, element) {
        var date = $(element).find(".NoteDate");
        var note = $(element).find(".NoteRight");

        date.height(note.height());
    });
});

But this is kinda slow because the notes are retrieved using Ajax and I have to do that call with async: false or the notes will not be fetched before the "each" runs.

So: It's possible to "translate" that code to the template? I tried something like:

<div class="NoteDate" 
     data-bind="style: { backgroundColor: background, 
                         color: color, height: $('.NoteRight').height() 开发者_开发知识库}">

But that doesn't work.

After even some more fiddling around, I have this function now (afterRender):

this.updateNotesLayout = function (elements) {
    var date = $(elements).find(".NoteDate");
    var note = $(elements).find(".NoteRight");
    alert(date.height());
    alert(note.height());
    date.height(note.height());
    alert(date.height());
}

But the date and note height is 0, but in the old example, the height was correct on both cases.

Any idea?


The easiest option to run code against elements rendered by a template is to use the afterRender callback of the template binding.

http://knockoutjs.com/documentation/template-binding.html#note_4_using_the__option

This will allow you to run code on your new nodes. In a foreach situation this runs for each item.

0

精彩评论

暂无评论...
验证码 换一张
取 消