Skip to content

Instantly share code, notes, and snippets.

@nezarfadle
Created August 18, 2019 12:43
Show Gist options
  • Save nezarfadle/557f0913a2ed97235b102433122b03c2 to your computer and use it in GitHub Desktop.
Save nezarfadle/557f0913a2ed97235b102433122b03c2 to your computer and use it in GitHub Desktop.
let observer = null;

Vue.directive('selectable', {
		
    	bind: function (el, binding) {
        
				let node = binding.value.node
        let prop = binding.value.prop
        let value = binding.value.value
				
        // Options for the observer (which mutations to observe)
        const config = { attributes: true };


        // Create an observer instance linked to the callback function
        observer = new MutationObserver(function(mutationsList, observer) {
        		node[prop] = value
        });

        // Start observing the target node for configured mutations
        observer.observe(el, config);
      },
      
      unbind: function (el) {
      	 observer.disconnect();
      }
    
})

new Vue({
  el: "#app",
  data: {
  	
    todos: [
    		{text: "Todo 1", selected: ""},
        {text: "Todo 2", selected: ""},
        {text: "Todo 3", selected: ""},
        {text: "Todo 4", selected: ""},
        {text: "Todo 5", selected: ""},
        {text: "Todo 6", selected: ""},
    ]
  },
  
  computed: {
  	selectedItems: function() {
    
    	return this.todos.filter( function(o){
      	return o.selected == "selected";
      })
    }
  }
})

$(function(){
	
$("#btn").click(function(){
    $("#app > div").first().addClass("selected")
  })
  
})
<div id="app">
  {{ selectedItems }}
  <div v-for="todo in todos" :class="todo.selected" v-selectable="{ node: todo, prop: 'selected', value: 'selected' }">{{ todo.text }}</div>
  <button id="btn">Select</button>
</div>


.selected
{
  background-color: red;
  padding: 20px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment