Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markdstafford/5977940 to your computer and use it in GitHub Desktop.
Save markdstafford/5977940 to your computer and use it in GitHub Desktop.
var queryString = ("/Northwind.svc/Products?"
+ "$filter=((Category/Category_ID eq 1)or"
+ "substringof('tofu',tolower"
+"(Product_Name)))&"
+ "$orderby=Category/Category_Name&"
+ "$select=Product_Name");
$.ajax({
url: queryString,
dataType: 'JSON',
success: function (result) {
var data;
if ((typeof result === 'object') && (('d' in result) && ('results' in result.d))) {
data = result.d.results;
} else {
data = result.d || result;
}
if (Array.isArray(data)) {
for (var i = 0; i < data.length; i++) {
var item = data[i][“Product_Name”];
...
} } else {
$('#products').append(data);
}
}
});
northwindContext
.Products
.filter(function (product) { return
product.Category.Category_ID == 1 ||
product.Product_Name
.toLowerCase().contains('tofu') })
.orderBy('it.Category.Category_Name')
.map(function(p) { return p.Product_Name } )
.forEach(function (productName) { ... } );
$data.Entity.extend('NorthwindModel.Product', {
'Product_ID': { 'key':true,'type':'Edm.Int32','nullable':false,'computed':true },
'Supplier_ID': { 'type':'Edm.Int32','nullable':true },
'Category_ID': { 'type':'Edm.Int32','nullable':true },
'Product_Name': { 'type':'Edm.String','nullable':false,'required':true,'maxLength':40 },
'Unit_Price': { 'type':'Edm.Decimal','nullable':true },
'Category': { 'type':'NorthwindModel.Category','inverseProperty':'Products' },
'Order_Details': { 'type':'Array','elementType':'NorthwindModel.Order_Detail','inverseProperty':'Product' }
// ...
});
$data.EntityContext.extend('NorthwindContext', {
'Products': { type: $data.EntitySet, elementType: NorthwindModel.Product },
'Categories': { type: $data.EntitySet, elementType: NorthwindModel.Category },
'Customers': { type: $data.EntitySet, elementType: NorthwindModel.Customer}
// ...
});
C:\NorthWindEditor>JaySvcUtil.exe -m http://localhost:50538/examples/$metadata
-o northwind.js
var context = new NortwindContext({
name: 'oData',
oDataServiceHost: 'http://localhost:50538/examples/Northwind.svc'
});
context.onReady(function () {
// work with your data
});
$data.initService('http://yourhost/yourODataService')
.then(function (context) {
// manage your data through context with JSLQ
});
<script src="Scripts/vendor/jquery-1.9.1.min.js"></script>
<script src="Scripts/vendor/datajs-1.0.3.min.js"></script>
<script src="Scripts/vendor/jaydata.js"></script>
<script src="Scripts/northwind.js"></script>
<table id="categoryTable" class="table span3 reset-m" style="margin: 0 10px 10px 0 !important;">
<thead>
<tr>
<th>Category name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
// main* – we will change this code in the second chapter
$(function () {
var oProviderConfig = {
name: 'oData',
oDataServiceHost: '/examples/Northwind.svc'
};
//initialize the Northwind context from the static data model generated by JaySvcUtil.exe
window['northwind'] = new JayDataExamples.NorthwindDB.NorthwindEntities(oProviderConfig);
northwind.onReady(function () {
northwind.Categories.toArray(renderCategories);
});
});
function renderCategories(dataList) {
var table = $('#categoryTable tbody');
table.empty();
dataList.forEach(function (item) {
table.append('<tr><td><a onClick="loadProduct(' + item.Category_ID + ')">' +
item.Category_Name + '</a></td><td>' + item.Description + '</td></tr>');
});
}
function loadProduct(categoryId) {
northwind.Products
.filter(function (product) { return product.Category_ID == this.Id },
{ Id: categoryId })
.toArray(renderProducts);
}
function renderProducts(dataList) {
$('.well-box').hide();
$('#productTable').show();
var table = $('#productTable tbody');
table.empty();
dataList.forEach(function (item) {
table.append('<tr><td><a onClick="editProduct(' + item.Product_ID + ')">'
+ item.Product_Name + '</a></td>'
+ '<td>' + item.English_Name + '</td>'
+ '<td>' + item.Unit_Price + '</td>'
+ '<td>' + item.Units_In_Stock + '</td>'
+ '<td>' + item.Discontinued + '</td></tr>');
});
}
<table id="productTable" class="table span6 reset-m hide" style="margin: 0 10px 10px 0 !important;">
<thead>
<tr>
<th>Product Name</th>
<th>English Name</th>
<th>Unit Price</th>
<th>Units In Stock</th>
<th>Discontinued</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div id="editProduct" class="table span3 reset-m noborder_">
<div class="well-box hide">
<form>
<fieldset>
<legend class="modal-header">Edit Product</legend>
<div class="modal-body" style="max-height: 600px;">
<div class="row-fluid">
<div class="span12">
Product name:
<br />
<input type="text" name="Product_Name" />
</div>
<div class="span12">
English Name:
<br />
<input type="text" name="English_Name" />
</div>
<div class="span12">
Unit Price:
<br />
<input type="text" name="Unit_Price" />
</div>
<div class="span12">
Units In Stock:
<br />
<input type="text" name="Units_In_Stock" />
</div>
<div class="span12">
Discontinued:
<input type="checkbox" name="Discontinued" checked />
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" value="save" class="btn btn-success tshadow" />
</div>
</fieldset>
</form>
</div>
<div id="saveResult" class="alert alert-success hide">
<strong>Success!</strong>
<br />
Product has been saved successfully.
</div>
</div>
function editProduct(productId) {
northwind.Products
.single(function (product) { return product.Product_ID == this.Id }, { Id: productId }, renderEditProduct);
}
function renderEditProduct(product) {
window.selectedProduct = product;
$('form').serializeArray().forEach(function (item) {
$('form [name="' + item.name + '"]').val(product[item.name]);
});
$('form [name="Discontinued"]').prop('checked', product['Discontinued']);
$('.well-box').show();
}
function saveProduct() {
//attach the selected product entity to JayData context
northwind.Products.attach(selectedProduct);
//collect the values from the form and
//modify the properties of our local entity
$('form').serializeArray().forEach(function (item) {
selectedProduct[item.name] = $('form [name="' + item.name + '"]').val();
});
selectedProduct.Discontinued = !!$('form [name = "Discontinued"]').attr('checked');
//save the modified product to our remote database through OData using JayData
northwind.saveChanges();
//display a message to the user
var result = $('#saveResult');
result.show();
setTimeout(function () {
result.fadeOut("slow");
}, 1500);
return false;
}
$data.initService('/examples/Northwind.svc').then(function (remoteDB, contextFactory, contexType) {
var localDB = contextFactory({ name: 'local', databaseName: 'Northwind' });
});
$(function () {
// sync entities from OData datasource to local DB using dynamic model
$data.initService('/examples/Northwind.svc').then(function (remoteDB, contextFactory, contexType) {
window['northwindRemote'] = remoteDB;
var localDB = contextFactory({ name: 'local', databaseName: 'Northwind' });
window['northwind'] = localDB;
$.when(remoteDB.onReady(), localDB.onReady())
.then(resetLocal)
.then(sync)
.then(function () {
$('form').bind('submit', saveProduct);
northwind.Categories.toArray(renderCategories);
});;
});
//clears entities from local database
function resetLocal() {
var categories = northwind.Categories.toArray();
var products = northwind.Products.toArray();
return $.when(categories, products)
.then(function (categories, products) {
categories.forEach(function (c) { northwind.Categories.remove(c); });
products.forEach(function (p) { northwind.Products.remove(p); });
return northwind.saveChanges();
});
}
//sync entities from OData to local database
function sync() {
var categories = northwindRemote.Categories.toArray();
var products = northwindRemote.Products.toArray();
return $.when(categories, products)
.then(function (categories, products) {
northwind.Categories.addMany(categories);
northwind.Products.addMany(products);
return northwind.saveChanges();
})
.fail(function (reason) {
console.log(reason);
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment