敲除js初始化元素内容中的可观察值 [英] Knockout js initialize the observable value from element content

查看:66
本文介绍了敲除js初始化元素内容中的可观察值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的东西

<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.

推荐答案

如果有必要,则可以使用自定义绑定很容易地做到这一点.

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

这里是一个绑定,它将使用元素的innerText设置现有的可观察对象,或者如果不存在则创建一个可观察对象.

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

示例: http://jsfiddle.net/rniemeyer/kKBBj/

这篇关于敲除js初始化元素内容中的可观察值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆