Thứ Hai, 30 tháng 11, 2015

Jquery widget factory setOptions and setOption

Can you please help I'm trying to understand the concept of setOptions and setOption in the widget factory.
In the code below I thought that if I changed the option color this.options.green += 1; then the _setOption would fire as there was a change to the options property.
Can you please help me understand the concept of setOptions and setOption as I read the documentation but am struggling. thanks for the help
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI Widget - Default functionality</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
  <!--<link rel="stylesheet" href="/resources/demos/style.css">-->
  <style>
  .custom-colorize {
    font-size: 20px;
    position: relative;
    width: 75px;
    height: 75px;
  }
  .custom-colorize-changer {
    font-size: 10px;
    position: absolute;
    right: 0;
    bottom: 0;
  }
  </style>
  <script>
      $(function () {

          $.widget("custom.colorize", {
              // default options
              options: {
                  red: 255,
                  green: 0,
                  blue: 0,
              },

              // the constructor
              _create: function () {
                  this.element.addClass("custom-colorize");

                  this.changer = $("<button>", {text: "change", "class": "custom-colorize-changer"}).appendTo(this.element);


                  this._on(this.changer, {click: "editMyColour"});
                  this._drawShape();
              },

              editMyColour: function (event) {
                  this.options.green += 1;
                  //alert('test');
                  //this._drawShape();
              },

              _drawShape: function () {
                  this.element.css("background-color", "rgb(" + this.options.red + "," + this.options.green + "," + this.options.blue + ")");

                  //this._trigger("change");
              },

              // _setOptions is called with a hash of all options that are changing
              // always refresh when changing options
              _setOptions: function () {
                  // _super and _superApply handle keeping the right this-context
                  this._superApply(arguments);
                  this._drawShape();
              },

              // _setOption is called for each individual option that is changing
              _setOption: function (key, value) {

                  this._super(key, value);
              }
          });

          // initialize with default options
          $("#my-widget1").colorize();



          // click to set options after initialization
          $("#black").click(function () {
              //$(":custom-colorize").colorize("option", {
              $('#my-widget1').colorize("option",{
                  red: 0,
                  green: 0,
                  blue: 0
              });
          });
      });
  </script>
</head>
<body>

<div>
  <div id="my-widget1">color me</div>
  <button id="disable">Toggle disabled option</button>
  <button id="black">Go black</button>
</div>


</body>
</html>
Answer:
this.options is accessing the options object directly. It is just an object--nothing is listening for a change to it. To do what you thought would happen, you would call _setOption, like this._setOption('green', this.options.green + 1);. The _setOption function is called when setting the option externally, like $('#my-widget1').colorize("option", "red", 0});

Or call this.option({'green': this.options.green + 1})

Sưu tầm từ: http://stackoverflow.com/questions/22333716/jquery-widget-factory-setoptions-and-setoption

Directive trong AngularJS

1.Directive là gì ?
Directive là 1 cặp thẻ HTML mở rộng do người dùng định ngĩa,nó làm nhiệm vụ mô tả dữ liệu,bạn đã làm việc với AngularJS cũng có thể biết 1 số cặp thẻ Directive kinh điển như ngApp (ng-app),ngController (ng-controller),ngRepeat(ng-repeat)..v.v
Directive được sử dụng để tùy chỉnh phần tử HTML và đơn giản hóa với thao tác DOM,Chúng ta có thể thay đổi đồng thời can thiệp vào DOM, bằng cách thêm chức năng tùy chỉnh, như datepicker một hoặc một widget autocomplete. AngularJS đi kèm với thiết lập riêng của mình được xây dựng trong hành động, cũng như khả năng để thêm những cái của riêng bạn định nghĩa
Bản chất chúng ta dùng Directive là để Js của chúng ta sử dụng lại (Directive có thể hoạt động độc lập như module).Mỗi 1 Derective cần có template và lấy dữ liệu ở scope và thông qua service link và compile để render thành 1 giao diện mong muốn.Trong Directive bạn cũng có thể định ngĩa hay sử dụng controller.

2.Dùng directive như thế nào?
Sử dụng Directive là khá dễ dàng,bạn chỉ cần đặt ở bất kỳ đâu,tùy thuộc nào cách xác định cho mục đích gì!
Ví dụ này được sử dụng lại ở trên cho cách khai báo :
<input datepicker>
or
<datepicker>


Cấu trúc của 1 Directive:


var myModule = angular.module(...);
myModule.directive('namespaceDirectiveName',
 function factory(injectables) {
var directiveDefinitionObject = {
restrict: string,
priority: number,
bindToController:bool,
template: string, templateUrl: string, replace: bool, transclude: bool, scope: bool or object, controller: function controllerConstructor($scope,$element,$attrs,$transclude), require: string, link: function postLink(scope, iElement, iAttrs) { ... }, compile: function compile(tElement, tAttrs, transclude) { return { pre: function preLink(scope, iElement, iAttrs, controller) { ... }, post: function postLink(scope, iElement, iAttrs, controller) { ... } } } }; return directiveDefinitionObject; });

  • Restrict:Được khai bao để Directive sử dụng như thế nào,nó có thể là element,attrbute,class,comment hay bất kỳ cách kết hợp nào (e.g: “EA,AC,AM…”)
  • Priority:Liên quan đến thứ tự thực hiện directive trong 1 DOM element(trong trường hợp bạn có nhiều directive mà việc sử dụng phải theo 1 thứ tự thì điều này là cần thiết.Số càng lớn sẽ được ưu tiên trước)
  • Template: kiểu string,nơi đây để viết template của bạn (không được sử dụng cho templateURL)
  • TemplateUrl:kiểu string,1 template được gọi từ url
  • Replace:True thay thế phần tử hiện tại,nếu false không thay thế lúc này sẽ thêm vào phần tử đó các phần tử khai báo trong directive
  • Transclude:cho phép bạn di chuyển template bên ngoài vào bên trong của directive để làm việc.
  • bindToController: true được dùng như controller cha, các controller con sẽ lấy được giá trị của nó
  • scope :tạo scope mới bên trong directive không kế thừa scope bên ngoài ( scope:{}: mặc định false, ngoài ra scope { } :namescope : ‘&’ thao tác với function, namescope : ‘@’ nhận vào là 1 string dữ liệu có thể thay đổi theo {{}},namescope:’=’ : dữ liệu chỉ được nhận từ 1 thành phần bên ngoài)
  • Controller: tạo 1 controller để xử lý công việc
  • Require:được sử dụng để gọi 1 thành phần bên ngoài
  • Link:có phạm khi hoạt động trong directive.tại đây sẽ làm việc trực tiếp với DOM element
  • Compile : thay đổi DOM template cho những directive là bản copi như việc bạn sử dụng ng-repeat.
Nào!!! Chúng ta cùng bắt đầu sử dụng Directive:
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="[add your bin description]"
<meta charset=utf-8 />
<title>Directive</title>
</head>
  <body ng-app="myApp">
    <my-directive>
   <script      src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"></script>
 <script>
      var app = angular.module("myApp",[])
      .directive("myDirective",function(){
        return {
          restrict:'E',
          template:'<p>Pham Minh Tai</p>'
        }
      })
 </script>
</body>
</html>
Ta khai báo 1 Directive có tên là “myDirective” và việc gọi nó ra chỉ cần cặp thẻ <my-directive> (thế là chúng ra có thể dùng thẻ html này ở đâu tùy thích,ở đây sử dụng tên khi gọi được viết theo kiểu “camelCase”).
1.Restrict (string) có 4 kiểu là:
  • ‘A’ : Attribute (nếu như bạn muốn dùng nó là Attribute <div my-directive></div>)
  • ‘E’ :Element sử dụng như ở trên
  • ‘C’ : class (sử dụng như 1 class <div class=”my-directive”></div>)
  • ‘M’ : Comment (bạn sử dụng nó như là 1 chú thích bất kì <!—my-directive —!>)
  • Bạn cũng có thể sử dụng 1 lúc tất cả restrict:’ECMA’
2.Template: (string)
Có 2 kiểu template một là template như khai báo ở trên,hai là dử dụng templateUrl để trỏ tới 1 template ở đâu mà bạn muốn sử dụng template đó.
Đôi khi ta cũng có thể dùng cách sau để gọi 1 templateUrl:
Ví dụ templateUrl sử dụng $templateCache:
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="[add your bin description]"
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body ng-app="myApp">
  <my-directive></my-directive>
   <script      src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"></script>
 <script>
  var app = angular.module("myApp",[])
  .run(function($templateCache){
    $templateCache.put('fileName.html','<div>hello word!!!</div>')
  })
  .directive("myDirective",function($templateCache){
    return {
      restrict:'E',
      templateUrl : 'fileName.html'
    }
  })
 </script>
</body>
</html>
Ví dụ sử dụng templateUrl với file đã tạo:
Index.html:
<div ng-controller="Ctrl">
       <my-directive>
    </div>
File scipt.js:
var app = angular.module("myApp",[])
      .directive("myDirective",function(){
        return {
          restrict:'E',
          templateUrl:'template.html'
        }
      })
      .controller("Ctrl",function($scope){
        $scope.dataUser = 
          {name:"Tai",pass:"123"}
      })
File template.html:
User: {{dataUser.name}} - Pass: {{dataUser.pass}}
Kết quả chạy chương trình : “User: Tai - Pass: 123”
Chúng ta cũng có thể tạo nhiều Controller để hiện thị và mỗi khi gọi 1 controller nhớ gọi ng-controller với tên controller khai báo nhé. Nhưng câu hỏi đặt ra là chúng ta cần khai báo 10 hay 100 hay 1000 controller thì khai báo bằng đó controller à??? Đó không phải là 1 giải pháp tốt.Có cách nào để 1 controller hoạt động mà vẫn sử dụng các tham số khác nhau không?
Từ đây Angular Directive sinh ra 1 khái niệm Isolate Scope (dịch nôm na là:cô lập phạm vi)
sopce : object or boolean
Chúng ta sẽ đi vào ví dụ cụ thể:
File index.html:
<div ng-controller="Ctrl">
       <my-directive info="user1"></my-directive> <br>
       <my-directive info="user2"></my-directive>
    </div>
Mỗi 1 Directive ta khai báo thêm 1 attribute chứa thông tin data cần tải (dữ liệu từ info này sẽ được Directive sử dụng)
Script.js
var app = angular.module("myApp",[])
      .directive("myDirective",function(){
        return {
          restrict:'E',
          templateUrl:'template.html',
          scope:{
            dataUserinfo: '=info'
          }
        }
      })
      .controller("Ctrl",function($scope){
        $scope.user1 = 
          {name:"Tai",pass:"123"}
        $scope.user2 = 
          {name:"Duyen",pass:"223"}
      })
Ở đây có 2 sự khác biệt đó là trong controller khai báo 2 scope user1 và user2 (đây chính là thông tin mà directive sẽ cần để lấy),công việc này do sopce có object dataUserinfo được gán từ attribute bên ngoài (“<my-directive info=’user1’>”) bằng cú pháp
scope : {dataUserinfo = info}
Với mỗi User được lấy từ attribute sẽ có cách gọi data là dataUserinfo.name, dataUserinfo.pass
Cụ thể :
User: {{dataUserinfo.name}} - Pass: {{dataUserinfo.pass}}
Đôi khi ta có thể viết như sau:
scope: { info : ‘@’ }
Cú pháp này sẽ hiểu lấy attribute là tham số truyền vào.Ví dụ sẽ có ở phần dưới
Kết quả chạy:
User: Tai - Pass: 123
User: Duyen - Pass: 223
Sưu tầm từ: http://angularjsviet.blogspot.com/2014/07/ajaj001-directive-trong-angularjs.html