javascript - knockout : Accessing property of observable object

标签 javascript ajax model-view-controller asp.net-web-api knockout.js

我是 knockoutjs 的新手,我正在关注有关如何通过 MVC Web API 使用 knockoutjs 的 Microsoft 教程,该教程位于此处:https://www.asp.net/web-api/overview/data/using-web-api-with-entity-framework/part-8 。本教程中的这一步解释了如何将“Book”对象分配给可观察对象,然后解释了要将对象的属性绑定(bind)到 html,我将像这样访问 AuthorName 属性:

data-bind="text: detail().AuthorName"

observable 和 ajax 调用如下所示:

self.detail = ko.observable();

self.getBookDetail = function (item) {
    ajaxHelper(booksUri + item.Id, 'GET').done(function (data) {
        self.detail(data);
    });
}

function ajaxHelper(uri, method, data) {
    self.error(''); // Clear error message
    return $.ajax({
        type: method,
        url: uri,
        dataType: 'json',
        contentType: 'application/json',
        data: data ? JSON.stringify(data) : null
    }).fail(function (jqXHR, textStatus, errorThrown) {
        self.error(errorThrown);
    });
}

我的问题是,如果我想从 javascript 访问 AuthorName 属性怎么办?我以为会是这样的,但这似乎行不通。我不确定这是否只是语法问题还是更复杂的问题:

self.detail().AuthorName

可以在此处下载此示例项目的完整源代码:https://github.com/MikeWasson/BookService

最佳答案

下面有两个带有示例 UI 的片段,尝试模拟您正在寻找的内容。我怀疑您没有使用 apply 绑定(bind)正确设置 View 模型,或者没有调用 getBookDetail 方法。

function ViewModel(){
    self = this;
  
    self.detail = ko.observable();

    self.getBookDetail = function () {
        var book = { AuthorName: 'foo', Category: 'bar'};
        self.detail(book);
    }
    
    self.getBookDetail();
}

ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="text:detail().AuthorName"></div>

function ViewModel(){
    self = this;
  
    self.detail = ko.observable();

    self.getBookDetail = function () {
        var book = { AuthorName: 'foo', Category: 'bar'};
        self.detail(book);
    }
   
}

ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="text:detail() !== undefined ? detail().AuthorName : '' "></div>
<input type="button" value="click" data-bind="click: getBookDetail"/>

关于javascript - knockout : Accessing property of observable object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41947273/

相关文章:

javascript - 在 jhipster 应用程序中使用 window.location 下载文件

JQuery Mobile 动态 ListView 过滤器不显示

ajax - WCAG 2.0 A 级和 AJAX 生成内容

c# - 使用 Layout = null 时丢失所有格式?

javascript - 在正文中加载脚本的顺序并使用 jquery ready

javascript - 对字符串的内部数组进行排序

iphone - View 或 View Controller 中的“逻辑”?

ios - 如何在 Swift Xcode 8.2 中以编程方式将导航 Controller 嵌入到选项卡栏 Controller 中?

javascript - 无法从 Controller 检索数据

javascript - Backbone.js - render() 在我在控制台中输入之前不起作用