Search code examples
knockout.jsknockout-mapping-plugin

Add attribute to ko model which mapped using mapping plugin


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


Solution

  • 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.