简体   繁体   中英

Knockoutjs: Accessing property of observable object

I'm new to knockoutjs and I'm following the Microsoft tutorial on how to use knockoutjs with MVC Web API located here: https://www.asp.net/web-api/overview/data/using-web-api-with-entity-framework/part-8 . This step in the tutorial explains how to assign a "Book" object to an observable, then explains that to bind the object's properties to html, I would access the AuthorName property like this:

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

The observable and ajax call looks like this:

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);
    });
}

My question is what if I want to access the AuthorName property from javascript? I thought it would be something like this but this doesn't seem to work. I'm not sure if it's just a syntax issue or something more complicated:

self.detail().AuthorName

This entire source code for this sample project can be downloaded here: https://github.com/MikeWasson/BookService

Below there are two snippets with a sample UI, that try to simulate that you are looking for. I suspect that either you don't have set up correctly the view model with the apply bindings or you don't call the getBookDetail method.

 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"/>

self.detail().AuthorName应该可以正常工作,但您需要确保self.detail()没有返回null或没有属性AuthorName的东西。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM