среда, 15 августа 2012 г.

work with SP Services(JQuery)

Hello!
I work with ruby, but have one task with SP.
I love coffee script, and write simple js class for SP.


class @QueryBuilder
  constructor: (@attrs) ->
    @constraine_query()
    @constraine_view()

  constraine_query: ->
    @query = "<Query>"
    if @attrs.query
      @query += "<Where><Eq>"
      for k,v of @attrs.hash
        @query += "<FieldRef Name= '#{k}'/><Value Type='#{v}'>#{@attrs.values[k]}</Value>"
      @query += "</Eq></Where>" if @attrs.hash?.length > 0
    @query += "</Query>"

  constraine_view: ->
    @caml_view = "<ViewFields >"
    for k,v of @attrs.hash
      @caml_view += "<FieldRef Name='#{k}' />"
    @caml_view += "</ViewFields>"

  prepend_query: (list_name, call_back_function)->
    $().SPServices({
    operation: "GetListItems",
    webURL: window.location.protocol + "//" + window.location.host,
    async: true,
    listName: list_name,
    CAMLViewFields: @caml_view,
    CAMLQuery: @query,
    completefunc: call_back_function
    })
Compile this into js.
For use this:
create some obj in js => obj = {}
obj.hash = {'some column name': 'type field'}
obj.value = {'some column name': 'value'}

next:
create simple obj =>
my_obj = new QueryBuilder(obj)
then
my_obj. prepend_query('list_name', function(xml_responce){console.log(xml_responce)})


And i have some simple helpers in js:


@xmlToJson = (attrs, xml) ->
  domElementArray = getZRows(xml)
  elements = []
  $.map domElementArray, (el) ->
    obj = {}
    for k,v of attrs
      obj["#{k}"] = $(el).attr("ows_#{k}").toString().strip_html()
    elements.push(obj)
  elements

@getZRows = (rXML) ->
  rows = undefined
  itemCount = $(rXML).find("rs\\:data").attr("ItemCount")
  if rXML.getElementsByTagName("z:row").length is 0 and itemCount is `undefined`
    rows = rXML.getElementsByTagNameNS("*", "row")
  else
    rows = rXML.getElementsByTagName("z:row")
  rows

String::strip_html = ->
  this.replace(/(<([^>]+)>)/ig,"")

Compile into js and use this!
Good day!