github github
  • Home
  • Pricing and Signup
  • Training
  • Gist
  • Blog
  • Login

jquery / jquery-datalink

  • Admin
  • Watch Unwatch
  • Fork
  • Your Fork
    • 139
    • 4
  • Source
  • Commits
  • Network (4)
  • Issues (4)
  • Graphs
  • Tree: 79ee55e

click here to add a description

click here to add a homepage

  • Switch Branches (1)
    • master
  • Switch Tags (0)
  • Comments
  • Contributors
Sending Request…
Downloads

A data linking plugin for jQuery. — Read more

  Cancel

  Cancel
  • HTTP
  • Git Read-Only

This URL has Read+Write access

Added contacts demo
InfinitiesLoop (author)
Wed Apr 28 11:56:25 -0700 2010
commit  79ee55e2924e561353e1
tree    31e1190500a471378c81
parent  1e789ea762cc61dc4fb9

Showing 5 changed files with 317 additions and 6 deletions.

A demo-contacts.css 34 •••••
A demo-contacts.html 147 •••••
A demo-contacts.js 0
M jQuery.livelink.js 11 ••••
A jquery.tmpl.js 131 •••••
Txt demo-contacts.css
  • View file @ 79ee55e
... ...
@@ -0,0 +1,34 @@
  1
+/*
  2
+css adapted from:
  3
+http://veerle.duoh.com/blog/comments/a_css_styled_table/
  4
+*/
  5
+    a {
  6
+        color: #6D929B;
  7
+    }
  8
+    .contacts {
  9
+        border: 1px solid #C1DAD7
  10
+    }
  11
+    .contacts td {
  12
+        border-right: 1px solid #C1DAD7;
  13
+        border-bottom: 1px solid #C1DAD7;
  14
+        padding: 6px 6px 6px 12px;
  15
+        color: #6D929B;
  16
+        vertical-align: top;
  17
+    }
  18
+    .contacts th {
  19
+        sans-serif;
  20
+        color: #6D929B;
  21
+        border-right: 1px solid #C1DAD7;
  22
+        border-bottom: 1px solid #C1DAD7;
  23
+        border-top: 1px solid #C1DAD7;
  24
+        letter-spacing: 2px;
  25
+        text-transform: uppercase;
  26
+        text-align: left;
  27
+        padding: 6px 6px 6px 12px;
  28
+    }    
  29
+    .phones td, .phones th {
  30
+        border: none;
  31
+        padding: 2px 2px 2px 4px;
  32
+        vertical-align: top;
  33
+    }
  34
+    
0 35
\ No newline at end of file
Txt demo-contacts.html
  • View file @ 79ee55e
... ...
@@ -0,0 +1,147 @@
  1
+<!DOCTYPE html> 
  2
+<html xmlns="http://www.w3.org/1999/xhtml"> 
  3
+<head>
  4
+    <title>My Contacts - Linking Demo</title>
  5
+    <link type="text/css" rel="Stylesheet" href="demo-contacts.css" />
  6
+<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
  7
+<script type="text/javascript" src="jquery.livelink.js"></script>
  8
+<script type="text/javascript" src="jquery.tmpl.js"></script>
  9
+<script type="text/javascript">
  10
+jQuery(function(){
  11
+
  12
+// define some basic default data to start with
  13
+var contacts = [
  14
+    { firstName: "Dave", lastName: "Reed", phones: [
  15
+        { type: "Mobile", number: "(555) 121-2121" },
  16
+        { type: "Home", number: "(555) 123-4567" } ]  },
  17
+    { firstName: "Joe", lastName: "Smith", phones: [
  18
+        { type: "Mobile", number: "(555) 444-2222" },
  19
+        { type: "Home", number: "(555) 999-1212" } ]  }
  20
+];
  21
+
  22
+// enable using 'contacts' as the name of the template
  23
+$.templates.contacts = $.tmpl($("#contacttmpl").html());
  24
+
  25
+$.extend($.convertFn, {
  26
+    // linking converter that normalizes phone numbers
  27
+    phone: function(value) {
  28
+        // turn a string phone number into a normalized one with dashes
  29
+        // and parens
  30
+        value = parseInt(value.replace(/[\(\)\- ]/g, ""), 10).toString();
  31
+        value = ("0000000000" + value).substr(-10);
  32
+        value = "(" + value.substr(0,3) + ") " + value.substr(3,3) + "-" + value.substr(6);
  33
+        return value;
  34
+    },
  35
+    fullname: function(value, settings) {
  36
+        return settings.source.firstName + " " + settings.source.lastName;
  37
+    }
  38
+});
  39
+
  40
+// show the results of the linking -- object graph is already full of the data
  41
+$("#save").click(function() {
  42
+    $("#results").html(JSON.stringify(contacts, null, 4));
  43
+});
  44
+
  45
+// add a new contact when clicking the insert button.
  46
+// notice that no code here exists that explicitly redraws
  47
+// the template.
  48
+$("#insert").click(function() {
  49
+    $.push(contacts, { firstName: "", lastName: "", phones: [] });
  50
+});
  51
+
  52
+// function that clears the current template and renders it with the
  53
+// current state of the global contacts variable.
  54
+function refresh() {
  55
+    $(".contacts").empty().append("contacts", {contacts:contacts});
  56
+    // bind inputs to the data items
  57
+    $(".contact").each(function(i) {
  58
+        var contact = contacts[i];
  59
+        $(".firstname", this).linkTo("val", contact, "firstName");
  60
+        $(".lastname", this).linkTo("val", contact, "lastName");
  61
+        $(".contact-fullname", this).linkFrom("text", contact, null, "fullname");
  62
+        $(".contact-remove", this).click(function() {
  63
+            $.splice(contacts, i, 1);
  64
+        });
  65
+        $(".phone", this).each(function(i) {
  66
+            var phone = contact.phones[i];
  67
+            $(".phone-type", this).linkTo("val", phone, "type");
  68
+            $(".phone-number", this).linkTo("val", phone, "number", "phone");
  69
+            $(".phone-remove", this).click(function() {
  70
+                // note: I'd like to only redraw the phones portion of the
  71
+                // template, but jquery.tmpl.js does not support nested templates
  72
+                // very easily. So here I am triggering an arrayChange event on
  73
+                // the main contacts array to force the entire thing to refresh.
  74
+                // Note that user input is not lost since the live linking has
  75
+                // already stored the values in the object graph.
  76
+                $.splice(contact.phones, i, 1);
  77
+                $([contacts]).trigger("arrayChange");
  78
+            });
  79
+        });
  80
+        $(".newphone", this).click(function() {
  81
+            $.push(contact.phones, { type: "", number: "" });
  82
+            $([contacts]).trigger("arrayChange");
  83
+        });
  84
+    });
  85
+}
  86
+
  87
+// subscribe to changes to the contact array, automatically refreshing
  88
+// the rendering of the template
  89
+$([contacts]).arrayChange(refresh);
  90
+
  91
+// initial view on load
  92
+refresh();
  93
+
  94
+
  95
+});
  96
+</script>
  97
+<script id="contacttmpl" type="text/html">
  98
+    <tr>
  99
+        <th>&nbsp;</th>
  100
+        <th>First Name</th>
  101
+        <th>Last Name</th>
  102
+        <th>Phone Numbers</th>
  103
+    </tr>
  104
+    {{each(i,contact) contacts}}
  105
+    <tr class="contact">
  106
+        <td><a href="#" class="contact-remove">remove</a></td>
  107
+        <td>
  108
+            <input class="firstname" type="text" value="${firstName}" />
  109
+            <div>
  110
+                full name: <span class="contact-fullname"></span>
  111
+            </div>
  112
+        </td>
  113
+        <td><input class="lastname" type="text" value="${lastName}" /></td>
  114
+        <td>
  115
+            <table class="phones">
  116
+                <tr>
  117
+                    <th>&nbsp;</th>
  118
+                    <th>Type</th>
  119
+                    <th>Number</th>
  120
+                </tr>
  121
+                {{each(i,city) phones}}
  122
+                <tr class="phone">
  123
+                    <td><a href="#" class="phone-remove">remove</td>
  124
+                    <td><input class="phone-type" type="text" value="${type}" /></td>
  125
+                    <td><input class="phone-number" type="text" value="${number}" /></td>
  126
+                </tr>
  127
+                {{/each}}
  128
+            </table>
  129
+            <a href="#" class="newphone">add new phone</a>
  130
+        </td>
  131
+    </tr>
  132
+    {{/each}}
  133
+</script>
  134
+</head>
  135
+
  136
+<body>
  137
+
  138
+<table class="contacts">
  139
+</table>
  140
+<input type="button" id="insert" value="Insert new contact" />
  141
+<input type="button" id="save" value="Save contacts" />
  142
+
  143
+<pre id="results">
  144
+</pre>
  145
+
  146
+</body>
  147
+</html>
0 148
\ No newline at end of file
Txt demo-contacts.js
  • View file @ 79ee55e
Binary file not shown
Txt jQuery.livelink.js
  • View file @ 79ee55e
... ...
@@ -117,8 +117,8 @@ $.each( ["attrChanging", "attrChange", "arrayChanging", "arrayChange"], function
117 117
             var old_handler = handleObj.handler;
118 118
             handleObj.handler = function( event, change ) {
119 119
                 var data = handleObj.data,
120  
-                    attrName = isattr ? change.attrName : change.change;
121  
-                if ( !data || data === attrName || $.inArray( attrName, data ) > -1 ) {
  120
+                    attrName = change ? (isattr ? change.attrName : change.change) : null;
  121
+                if ( !change || !data || data === attrName || $.inArray( attrName, data ) > -1 ) {
122 122
                     $.extend( event, change );
123 123
                     // todo: support extra parameters passed to trigger as
124 124
                     // trigger('attrChange', [<change>, extra1, extra2]).
... ...
@@ -171,13 +171,12 @@ $.link = function( settings ) {
171 171
         if ( ev ) {
172 172
             newValue = ev.newValue;
173 173
         }
174  
-        else if ( sourceAttr.indexOf( "data:" ) === 0 ) {
  174
+        else if ( sourceAttr && sourceAttr.indexOf( "data:" ) === 0 ) {
175 175
             newValue = source.data( sourceAttr.substr( 5 ) );
176 176
         }
177  
-        else {
178  
-            newValue = source.attr( sourceAttr );
  177
+        else if ( sourceAttr ) {
  178
+            newValue = sourceAttr === "val" ? source.val() : source.attr( sourceAttr );
179 179
         }
180  
-        var newValue = ev ? ev.newValue : ( isVal ? source.val() : source.attr( sourceAttr ) );
181 180
         if ( convert ) {
182 181
             newValue = convert( newValue, settings );
183 182
         }
Txt jquery.tmpl.js
  • View file @ 79ee55e
... ...
@@ -0,0 +1,131 @@
  1
+/*
  2
+ * jQuery Templating Plugin
  3
+ *   NOTE: Created for demonstration purposes.
  4
+ * Copyright 2010, John Resig
  5
+ * Dual licensed under the MIT or GPL Version 2 licenses.
  6
+ */
  7
+(function(jQuery){
  8
+  // Override the DOM manipulation function
  9
+  var oldManip = jQuery.fn.domManip;
  10
+  
  11
+  jQuery.fn.extend({
  12
+    render: function( data ) {
  13
+      return this.map(function(i, tmpl){
  14
+        return jQuery.render( tmpl, data );
  15
+      });
  16
+    },
  17
+    
  18
+    // This will allow us to do: .append( "template", dataObject )
  19
+    domManip: function( args ) {
  20
+      // This appears to be a bug in the appendTo, etc. implementation
  21
+      // it should be doing .call() instead of .apply(). See #6227
  22
+      if ( args.length > 1 && args[0].nodeType ) {
  23
+        arguments[0] = [ jQuery.makeArray(args) ];
  24
+      }
  25
+
  26
+      if ( args.length === 2 && typeof args[0] === "string" && typeof args[1] !== "string" ) {
  27
+        arguments[0] = [ jQuery.render( args[0], args[1] ) ];
  28
+      }
  29
+      
  30
+      return oldManip.apply( this, arguments );
  31
+    }
  32
+  });
  33
+  
  34
+  jQuery.extend({
  35
+    render: function( tmpl, data ) {
  36
+      var fn;
  37
+      
  38
+      // Use a pre-defined template, if available
  39
+      if ( jQuery.templates[ tmpl ] ) {
  40
+        fn = jQuery.templates[ tmpl ];
  41
+        
  42
+      // We're pulling from a script node
  43
+      } else if ( tmpl.nodeType ) {
  44
+        var node = tmpl, elemData = jQuery.data( node );
  45
+        fn = elemData.tmpl || jQuery.tmpl( node.innerHTML );
  46
+      }
  47
+
  48
+      fn = fn || jQuery.tmpl( tmpl );
  49
+      
  50
+      // We assume that if the template string is being passed directly
  51
+      // in the user doesn't want it cached. They can stick it in
  52
+      // jQuery.templates to cache it.
  53
+
  54
+      if ( jQuery.isArray( data ) ) {
  55
+        return jQuery.map( data, function( data, i ) {
  56
+          return fn.call( data, jQuery, data, i );
  57
+        });
  58
+
  59
+      } else {
  60
+        return fn.call( data, jQuery, data, 0 );
  61
+      }
  62
+    },
  63
+    
  64
+    // You can stick pre-built template functions here
  65
+    templates: {},
  66
+
  67
+    /*
  68
+     * For example, someone could do:
  69
+     *   jQuery.templates.foo = jQuery.tmpl("some long templating string");
  70
+     *   $("#test").append("foo", data);
  71
+     */
  72
+
  73
+    tmplcmd: {
  74
+      each: {
  75
+        _default: [ null, "$i" ],
  76
+        prefix: "jQuery.each($1,function($2){with(this){",
  77
+        suffix: "}});"
  78
+      },
  79
+      "if": {
  80
+        prefix: "if($1){",
  81
+        suffix: "}"
  82
+      },
  83
+      "else": {
  84
+        prefix: "}else{"
  85
+      },
  86
+      html: {
  87
+        prefix: "_.push(typeof $1==='function'?$1.call(this):$1);"
  88
+      },
  89
+      "=": {
  90
+        _default: [ "this" ],
  91
+        prefix: "_.push($.encode(typeof $1==='function'?$1.call(this):$1));"
  92
+      }
  93
+    },
  94
+
  95
+    encode: function( text ) {
  96
+      return text != null ? document.createTextNode( text.toString() ).nodeValue : "";
  97
+    },
  98
+
  99
+    tmpl: function(str, data, i) {
  100
+      // Generate a reusable function that will serve as a template
  101
+      // generator (and which will be cached).
  102
+      var fn = new Function("jQuery","$data","$i",
  103
+        "var $=jQuery,_=[];_.data=$data;_.index=$i;" +
  104
+
  105
+        // Introduce the data as local variables using with(){}
  106
+        "with($data){_.push('" +
  107
+
  108
+        // Convert the template into pure JavaScript
  109
+        str
  110
+          .replace(/[\r\t\n]/g, " ")
  111
+          .replace(/\${([^}]*)}/g, "{{= $1}}")
  112
+          .replace(/{{(\/?)(\w+|.)(?:\((.*?)\))?(?: (.*?))?}}/g, function(all, slash, type, fnargs, args) {
  113
+            var tmpl = jQuery.tmplcmd[ type ];
  114
+
  115
+            if ( !tmpl ) {
  116
+              throw "Template not found: " + type;
  117
+            }
  118
+
  119
+            var def = tmpl._default;
  120
+
  121
+            return "');" + tmpl[slash ? "suffix" : "prefix"]
  122
+              .split("$1").join(args || def[0])
  123
+              .split("$2").join(fnargs || def[1]) + "_.push('";
  124
+          })
  125
+        + "');}return $(_.join('')).get();");
  126
+
  127
+      // Provide some basic currying to the user
  128
+      return data ? fn.call( this, jQuery, data, i ) : fn;
  129
+    }
  130
+  });
  131
+})(jQuery);
0 132
\ No newline at end of file

0 notes on commit 79ee55e

Please log in to comment.
Dedicated Server Powered by the Dedicated Servers and
Cloud Computing of Rackspace Hosting®
  • Blog
  • Support
  • Training
  • Job Board
  • Shop
  • Contact
  • API
  • Status
  • © 2010 GitHub Inc. All rights reserved.
  • Terms of Service
  • Privacy
  • Security
  • English
  • Deutsch
  • Français
  • 日本語
  • Português (BR)
  • Русский
  • 中文
  • See all available languages

Your current locale selection: English. Choose another?

  • English
  • Afrikaans
  • Català
  • Čeština
  • Deutsch
  • Español
  • Français
  • Hrvatski
  • Indonesia
  • Italiano
  • 日本語
  • Nederlands
  • Norsk
  • Polski
  • Português (BR)
  • Русский
  • Српски
  • Svenska
  • 中文

Keyboard Shortcuts

Site wide shortcuts

s
Focus site search
?
Bring up this help dialog

Commit list

j
Move selected down
k
Move selected up
t
Open tree
p
Open parent
c or o or enter
Open commit

Pull request list

j
Move selected down
k
Move selected up
o or enter
Open issue

Issues

j
Move selected down
k
Move selected up
x
Toggle select target
o or enter
Open issue
I
Mark selected as read
U
Mark selected as unread
e
Close selected
y
Remove selected from view
c
Create issue
l
Create label
i
Back to inbox
u
Back to issues
/
Focus issues search

Network Graph

← or h
Scroll left
→ or l
Scroll right
↑ or k
Scroll up
↓ or j
Scroll down
t
Toggle visibility of head labels
shift ← or shift h
Scroll all the way left
shift → or shift l
Scroll all the way right
shift ↑ or shift k
Scroll all the way up
shift ↓ or shift j
Scroll all the way down