Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
522 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 Answer

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...