Search code examples
typescriptnativescriptnativescript-telerik-ui

NativeScript: Binding SearchBar submit event with view-model function/method?


Hi I am having trouble binding NativeScript Searchbar submit event with a method I have declared inside the vew-model.ts.

`<SearchBar id="searchBar" hint="Search" text=""  clear="onClear" submit="{{ onSubmit }}"/>`

And the function in viewmodel:

`public onSubmit(args) {
        console.log('pressed');
        let searchBar = <SearchBar>args.object;
        var searchPhrase = searchBar.text;
        this.url = this.url+this.searchPhrase;
        this.getItems(this.url);
        console.log(this.url);
    }`

But this doesn't seem to be working. If I define the same method inside the code-behind file (main-page.ts) it's called no matter if I write it as:

`<SearchBar id="searchBar" hint="Search" text=""  clear="onClear" submit=" onSubmit"/>`

OR

`<SearchBar id="searchBar" hint="Search" text=""  clear="onClear" submit="{{ onSubmit }}"/>`

I am new to NativeScript and I don't know if I am missing anything. I did check this answer and it didn't help because that was for TextFields. Any help will be appreciated. Thanks!


Solution

  • onSubmit should be a property of ViewModel in order to do event binding. Update the method as below.

    onSubmit = (args) => {
        console.log('pressed');
        let searchBar = <SearchBar>args.object;
        var searchPhrase = searchBar.text;
        this.url = this.url+this.searchPhrase;
        this.getItems(this.url);
        console.log(this.url);
    };