Knockout.js点击绑定访问模型值

时间:2014-03-13 21:37:29

标签: javascript knockout.js

当警告对象内的属性值时,我收到一条非常奇怪的警报消息。

警报电话位于它所说的问题 *

我收到的提醒是https://flic.kr/p/m1CYkD function c(){if0<arguments.length)returnc.equalityComparer&&c.equalityComparer(d,arguments[0])} ......

JS

$(function(){
  ko.applyBindings(new ViewModelBooks());
});


function Book(title, checked_out_to, id)
{
  this.title = ko.observable(title);
  this.checked_out_to = ko.observable(checked_out_to);
  this.id = ko.observable(id);
}

function ViewModelBooks(){
  var self = this;
  self.library = ko.observableArray();

  self.checkOutBook = function(obj){
    alert(obj.title); <--- ISSUE IS HERE ********************
  };

  // Query all books
  var url = 'http://portal.internal.urs.org/tools_services/training_library/_vti_bin/listdata.svc/Book?$expand=CheckedOutTo';
  $.getJSON(url, function(data){
    for (var i = 0; i < data.d.results.length; i++){
        var book = data.d.results[i];
        var checked_out_to = null;

        if (book.CheckedOutTo != null){
          checked_out_to = book.CheckedOutTo.Name;
        }
        self.library.push(new Book(book.Title, checked_out_to, book.Id));
    }
  });
}

HTML

<tbody data-bind="foreach: library">
        <tr><td data-bind="text: title"></td>
            <td>
                <span data-bind="ifnot: checked_out_to">
                    <button class="btn_checkout" type="button" 
                    data-bind="click: $parent.checkOutBook">Check Out</button>
                </span>
                <span data-bind="if: checked_out_to">
                    <span data-bind="text: checked_out_to"> </span>
                </span>
            </td>
        </tr>
    </tbody>

由于

1 个答案:

答案 0 :(得分:3)

由于obj.titleobservable(函数),如果需要它,则必须调用它。

您的代码应为:

alert(obj.title()); // getter
obj.title('new value');  // setter

<强> See doc