Knockout没有绑定值

时间:2012-02-24 07:32:09

标签: javascript jquery data-binding knockout.js

您好我有以下情况。我有一个with块分配给一个属性。当此属性为null时,内容不存在。但是当一个人放置属性标记时应该生成。

HTML:

<!-- ko with: Gallery -->
<div class="GalleryMain">
    <a href="#" data-bind="attr: {href: Current.Zoomed}" class="cloud-zoom" id="TargetZoom">
        <img data-bind="attr: {src: Current.Main}" alt="" />
     </a>
     <span data-bind="text: Current.Zoomed"></span>
    <span data-bind="text: Current.Main"></span>
</div>
​<!-- /ko -->
<a href="javascript:;" id="Do">Update property</a>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

JavaScript的:

function PrimaryViewModel() {
    var self = this;
    this.Gallery = ko.observable(null);
    this.Exit = function() {
        self.Gallery(null);
    }
}
var Picture = (function() {
    function _Constructor(input) {
        this.Zoomed = ko.observable(input.Zoomed);
        this.Main = ko.observable(input.Main);
        this.Thumb = ko.observable(input.Thumb);
    }
    _Constructor.Width = 489;
    _Constructor.Height = 835;
    return _Constructor;
})();

function GalleryViewModel(data, current) {
    var self = this;
    this.Pictures = ko.observableArray($.map(data, function(input) {
        return new Picture(input);
    }));

    var all = this.Pictures();
    this.Current = ko.observable(all[0]);
    for (var i = 0; i < all.length; i++)
        if (all[i].Main == current) 
            this.Current(all[i]);
    this.SetCurrent = function() {
        self.Current(this);
    }
}
$(function() {
    var viewModel = new PrimaryViewModel();
    $("#Do").click(function() {
        var data = [{
            "Zoomed": "Content/Big/1Z.jpg",
            "Main": "Content/Big/1.jpg",
            "Thumb": "Content/Images/Thumbs/1.jpg"},
        {
            "Zoomed": "Content/Big/2Z.jpg",
            "Main": "Content/Big/2.jpg",
            "Thumb": "Content/Images/Thumbs/2.jpg"},
        {
            "Zoomed": "Content/Big/3Z.jpg",
            "Main": "Content/Big/3.jpg",
            "Thumb": "Content/Images/Thumbs/B1.jpg"},
        {
            "Zoomed": "Content/Big/4Z.jpg",
            "Main": "Content/Big/4.jpg",
            "Thumb": "Content/Images/Thumbs/3.jpg"},
        {
            "Zoomed": "Content/Big/15.jpg",
            "Main": "Content/Big/5.jpg",
            "Thumb": "Content/Images/Thumbs/B2.jpg"}];
        viewModel.Gallery(new GalleryViewModel(data, "Content/Big/1.jpg"));
    });
    ko.applyBindings(viewModel);
});​

Fiddle

Update property按钮后,正在生成html,但不会发生绑定。请帮帮我。

2 个答案:

答案 0 :(得分:1)

我已经解决了我的问题。这个问题非常隐蔽,因为总是在“JavaScripting”时发生。

<span data-bind="text: Current.Zoomed"></span>
<span data-bind="text: Current.Main"></span>

它试图捕获Zoomed可观察的Current属性。

<span data-bind="text: Current().Zoomed"></span>
<span data-bind="text: Current().Main"></span>

添加括号将提取包含Zoomed属性的目标对象。

答案 1 :(得分:0)

我看了一下,看起来没问题。我已经更新了你的小提琴,列出了图片的数量和他们的'缩放'名称作为输入框,只是一个普通的列表,一切正常。如果编辑缩放名称,则缩放名称列表会自动更新。

http://jsfiddle.net/unklefolk/kKc6R/5/

希望我不会错过任何东西!