Two way binding not working on bootstrap-select with aurelia

人盡茶涼 提交于 2019-12-02 01:37:06

Turns out to be a simple scope issue:

attached(){
  $('.selectpicker').selectpicker({
       style: 'btn-info',
       size: 4
  });

 $('.selectpicker').on('change', function(){
    var selected = $(this).find("option:selected").val();

     this.selectedValue = selected; // <-- This here doesn't refer to the VM any more
     // if you look at the line above you are wrapping $(this) with jq, this works 
     // because 'this' is now in the scope of the calling element but 
     // doesn't refer to the aurelia viewmodel
     console.log(this.selectedValue);
  });

   $('.selectpicker').val(this.selectedValue); 
   $('.selectpicker').selectpicker('refresh');

 }

Simple fix is:

attached(){

  var self = this; // <--- Create a ref to the VM

$('.selectpicker').selectpicker({
       style: 'btn-info',
       size: 4
  });

 $('.selectpicker').on('change', function(){
    var selected = $(this).find("option:selected").val();
     // Change this to self
     self.selectedValue = selected; // <--- Correct object gets the value now - binding works
     console.log(this.selectedValue);
  });

   $('.selectpicker').val(this.selectedValue); 
   $('.selectpicker').selectpicker('refresh');

 }

I'm not sure how this will actually be handled in ES6/7 - I'm sure I read somewhere about how this will change, but since you are transpiling to ES5 it's definitely something to watch out for

The following code works for me, in case anyone has the same issue:

import {inject, customElement, bindable} from 'aurelia-framework';
import 'bootstrap-select'

@customElement('select-picker')
@inject(Element)
export class BootStrapSelectPicker {
    @bindable name: string;
    @bindable selectableValues;
    @bindable selectedValue;

    constructor(private element) {
    }

    attached() {
        var self = this;
        var $: any = jQuery;
        var $elm = $(self.element).find('select');
        if ($elm.length > 0) {
            $elm.selectpicker();
            $elm.on('change', function () {
                self.selectedValue = $(this).find("option:selected").val();
            });
            this.refreshPicker($elm);
        }
    }

    selectedValueChanged(newValue, oldValue) {
        var $: any = jQuery;        
        var $elm = $(this.element).find('select');
        this.refreshPicker($elm);
    }

    private refreshPicker = ($elm) => {        
        $elm.val(this.selectedValue);
        $elm.selectpicker('refresh');        
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!