Knockout.js - javascript function on data-bind

后端 未结 5 1477
天命终不由人
天命终不由人 2021-02-12 12:38

Is there a way i can call JavaScript function on data-bind like this:



        
相关标签:
5条回答
  • 2021-02-12 12:45

    You can use arbitrary JavaScript expressions for bindings, but keep in mind that they are evaluated in the viewmodel's context, so all functions in the expression have to be properties of viewmodel. In your case, MySomeFunction has to be a property of your viewmodel. If you create your viewmodel using mapping plugin, you can attach additional functions to the viewmodel like this:

    var viewModel = ko.mapping.fromJS(data.d)
    viewModel.MySomeFunction = function(...){...};
    
    0 讨论(0)
  • 2021-02-12 12:45

    Well I am just going through the tutorial myself but I thought you had to set up a property and use ko.computed to give it its value (from the tutorial):

    function AppViewModel() {
    this.firstName = ko.observable("Bert");
    this.lastName = ko.observable("Bertington");
    this.fullName = ko.computed(function(){ 
      return this.firstName() + " " + this.lastName(); 
      },this);
    }
    

    Then you can have:

    Full name: <strong data-bind="text: fullName"></strong>
    
    0 讨论(0)
  • 2021-02-12 12:49
    <div style="font-size:18px;float:left;width:95%" data-bind="html: trimString(AccountName,25)"></div>
    
    function trimString(value, maxLen) {
    
        //Return undefined, and short strings
        if (value === undefined) return undefined;
        if (value.length < maxLen) return value;
    
        return value.substring(0, (maxLen - 1));    
    }
    
    0 讨论(0)
  • 2021-02-12 12:52

    I had a similar problem trying to calculate table cell entries. What worked for me was including 'MySomeFunction' in my data model, and then data-binding my table cells as:

    <td data-bind="text: $root.MySomeFunction(SomeProperty)"></td>
    
    0 讨论(0)
  • 2021-02-12 13:00

    I have managed to do this by using the context. If you need the whole code I can send it to you.

    <h2 class="text" data-bind="html: currentProgram($context)"></h2>
    
    function currentProgram(context){
      var title = '<font size="1">' + context.$data.name + '</font>';
      return title;
    }
    

    You will also need to set this

           $.ajaxSetup({
              async: false
            });
    
    0 讨论(0)
提交回复
热议问题