Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update model from custom directive VueJS

I currently use Vue.JS 2.0 and I want to update the model off one Vue instance from an custom directive, but im looking a nice way to do it, this is because i trying to create an custom directive that implement JQueryUI-Datepicker the code is the follow:

<input type="text" v-datepicker="app.date" readonly="readonly"/>

Vue.directive('datepicker', {
  bind: function (el, binding) {
    $(el).datepicker({
      onSelect: function (date) {
        //this is executed every time i choose an date from datepicker
        //pop.app.date = date; //this work find but is not dynamic to parent and is very dirty
        Vue.set(pop, binding.expression, date); //this should work but nop
      }
    });
  },
  update: function (el, binding) {
    $(el).datepicker('setDate', binding.value);
  }
});

var pop = new Vue({
    el: '#popApp',
    data: {
        app: {
            date: ''
        }
    }
});

Someone know how to update pop.app.date in a dynamic way from the directive, i know that binding.expression return in this example app.date and date return the current date picked in the datepicker but i dont know how to update the model from the directive

like image 823
David Arreola Avatar asked Oct 12 '16 22:10

David Arreola


1 Answers

This will do the trick:

// vnode (third argument is required).
bind: function (el, binding, vnode) {
    $(el).datepicker({
        onSelect: function (date) {
            // Set value on the binding expression.
            // Here we set the date (see last argument).
            (function set(obj, str, val) {
                str = str.split('.');
                while (str.length > 1) {
                    obj = obj[str.shift()];
                }
                return obj[str.shift()] = val;
             })(vnode.context, binding.expression, date);
         }
    });
},

Reference: https://stackoverflow.com/a/10934946/2938326

like image 141
Kamal Khan Avatar answered Nov 20 '22 17:11

Kamal Khan