I have added new attributes to a mapped object in knockout js.I could access added attributes in table. but when I loaded a object to another view it does not show the added attributes, but I can access mapped attribute in that UI

function Ticket(jsTicket){
   var self = this;
   ko.mapping.fromJS(jsTicket, {}, this);
   this.company = "Gover";
   this.formattedDate = moment(self.date(),"YYYY-MM-DDTHH:mm:ss").format("MM-DD HH:MM");
   //This method call to another page, I could access js attribute in that UI but 
   // couldn't access manually added attributes,what would be the solution to this
   this.getRunTicket = function(){
     servicet.getTicket(self);
   }
}

html page

<div data-role="page" id="rticketDetailsPage" data-theme="b">
       <div data-role="content" data-theme="b" data-position="fixed">
           <!-- mapped attribute from JS --> 
           <p>NO : <span data-bind="text: ticketNumber()"></p>
           <!-- Manually added attributes -->    
           <p>Date : <span data-bind="text: formattedDate()"></p>
           <p>Company : <span data-bind="text: company()"></p>
       </div>
   </>

Data grid Model

function DataGrid(){
    var self = this;
    self.dataGrid = ko.observableArray();

    self.addTicketToGrid = function(ticket){
        self.dataGrid.push(ticket);
    }
}

Data grid html

<tbody data-bind="foreach : dataGrid">
      <tr>
        <td><span data-bind="text : number(),click: getTicket"></span></td>
        <!-- formatted date is manually added attribute,displays in grid-->
        <td><span data-bind="text : formattedDate()></span></td>
        <td><span data-bind="text : operatorName()"></span></td>
      </tr>
</tbody>

Why I couldn't access manually added added attribute within that scope?

Thank you in advance

有帮助吗?

解决方案

company and formattedDate aren't observables, but you're trying to access them as if they were. They're plain strings but your bindings try to call them as functions.

其他提示

The way you should add attributes to a mapped object is through the create function on your mapping definition (the 2nd argument to ko.mapping.fromJS).

var mapping = {
    create: function(opts) {
        var result = ko.mapping.fromJS(opts.data);
        result.company = ko.observable("Gover");
        return result;
    }
};

Then in your Ticket constructor

ko.mapping.fromJS(jsTicket, mapping, this);

That should help resolve your issue because the object will now always have the additional properties.

Another piece of advice is to use custom bindings or at least computed values to format dates in your table.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top