Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

javascript - Knockout js initialize the observable value from element content

I have some thing like this

<td data-bind="text: email_sended">
  <%= invite.email_send %>
</td>

function AdminInvitesViewModel() {
   var self = this;
   self.email_send = ko.observable();
}

ko.applyBindings(new AdminInvitesViewModel());

how can i initialize the observable from the content of the container ?

I this case the email send is a true/false value.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If this is necessary, then you can do this pretty easily with a custom binding.

Here is a binding that would set an existing observable using the element's innerText or create an observable if it doesn't exist.

ko.bindingHandlers.textWithInit = {
    init: function(element, valueAccessor, allBindingsAccessor, data) {
        var property = valueAccessor(),
            content = element.innerText || element.textContent;

        //create the observable, if it doesn't exist 
        if (!ko.isWriteableObservable(data[property])) {
            data[property] = ko.observable();
        }

        data[property](content);

        ko.applyBindingsToNode(element, { text: data[property] });
    }
};

You would use it like:

<div data-bind="textWithInit: 'email_sended'"></div>

Note that the property name is in quotes, as the binding supports the observable not existing yet

Sample: http://jsfiddle.net/rniemeyer/kKBBj/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...